import { defineStore } from 'pinia'
import { messagesApi } from '../utils/apiService'
import { useUserStore } from './user'

export const useActivityStore = defineStore('activity', {
    state: () => ({
        activities: [],
        page: 1,
        pageSize: 10,
        total: 0,
        loading: false,
        hasMore: true
    }),

    getters: {
        recentActivities: (state) => {
            return [...state.activities].sort((a, b) => new Date(b.time) - new Date(a.time))
        },

        activityByLocation: (state) => (locationId) => {
            return state.activities.filter(activity => activity.locationId === locationId)
                .sort((a, b) => new Date(b.time) - new Date(a.time))
        },

        activityByUser: (state) => (userId) => {
            return state.activities.filter(activity => activity.userId === userId)
                .sort((a, b) => new Date(b.time) - new Date(a.time))
        }
    },

    actions: {
        async fetchRecentActivities(userId = null, page = null) {
            // 如果未提供userId，则从userStore获取
            if (!userId) {
                const userStore = useUserStore();
                userId = userStore.getUser?.id;

                if (!userId) {
                    console.warn('无法获取用户ID，无法获取活动记录');
                    return false;
                }
            }

            console.log('开始获取活动记录，用户ID:', userId, '页码:', page || this.page);
            this.loading = true;

            try {
                // 使用新的消息API获取活动数据
                const response = await messagesApi.getMessages({
                    userId: userId,
                    page: page || this.page,
                    pageSize: this.pageSize
                });

                console.log('API返回消息数据:', response);

                if (response && response.code === 200 && response.data) {
                    // 转换后端数据格式为前端格式
                    const allMessages = response.data.list || [];
                    console.log('服务器返回的原始消息列表:', allMessages);

                    // 修改过滤条件，包括通知类型中的登录相关消息
                    const activityList = allMessages.filter(item => {
                        // 调试每条消息
                        console.log('处理消息:', item);

                        // 活动类型消息
                        const isActivityMessage =
                            item.messageType === 'activity' &&
                            ['create', 'update', 'delete', 'move', 'login', 'logout', 'permission'].includes(item.subType);

                        // 通知类型中的登录相关消息
                        const isLoginNotification =
                            item.messageType === 'notification' &&
                            ['login', 'logout', 'permission'].includes(item.subType);

                        // 记录每条消息的筛选结果
                        console.log(`消息ID ${item.id}: `, {
                            messageType: item.messageType,
                            subType: item.subType,
                            isActivityMessage,
                            isLoginNotification,
                            result: isActivityMessage || isLoginNotification
                        });

                        return isActivityMessage || isLoginNotification;
                    });

                    console.log('过滤后的消息列表 (共 ' + activityList.length + ' 条):', activityList);

                    if (activityList.length === 0) {
                        console.warn('没有找到活动或登录通知记录');
                        // 添加检查：如果我们确实有原始数据但过滤后为空，检查原因
                        if (allMessages.length > 0) {
                            console.warn('原始消息列表中有数据，但过滤后没有活动记录。检查原始数据:');
                            allMessages.forEach((item, index) => {
                                console.log(`[${index}]消息类型: ${item.messageType}, 子类型: ${item.subType}`);
                            });
                        }

                        if (page === 1 || this.page === 1) {
                            this.activities = []; // 如果服务器返回空列表，则清空本地数据
                            console.log('已清空本地活动数据');
                        }

                        this.total = response.data.total || 0;
                        this.hasMore = false;
                        this.page = page || this.page;

                        return true;
                    }

                    const mappedActivities = activityList.map(item => {
                        // 为每条记录添加详细日志
                        console.log('映射消息 ID:', item.id, 'Type:', item.messageType, 'SubType:', item.subType);

                        return {
                            id: item.id,
                            title: item.title,
                            content: item.content,
                            actionType: item.subType,
                            time: item.createTime,
                            userName: item.userName || (item.userId ? '用户' : '系统'),
                            locationName: item.locationName || '',
                            userId: item.userId,
                            locationId: item.locationId,
                            itemId: item.itemId,
                            itemName: item.itemName
                        };
                    });

                    console.log('最终活动列表:', mappedActivities);

                    // 如果是第一页，替换现有活动；否则追加
                    if (page === 1 || this.page === 1) {
                        this.activities = mappedActivities;
                        console.log('已用后端数据替换默认活动数据，共 ' + mappedActivities.length + ' 条记录');
                    } else {
                        this.activities = [...this.activities, ...mappedActivities];
                        console.log('已添加 ' + mappedActivities.length + ' 条记录到现有活动数据');
                    }

                    this.total = response.data.total || 0;
                    this.hasMore = this.activities.length < this.total;
                    this.page = page || this.page;

                    console.log(`成功获取到 ${mappedActivities.length} 条活动记录，总计: ${this.total} 条`);
                    return true;
                } else {
                    console.warn('API返回的活动数据无效:', response);
                    // 返回空数组，不再保留默认模拟数据
                    if (page === 1 || this.page === 1) {
                        this.activities = [];
                        console.warn('API返回无效数据，已清空本地活动数据');
                    }
                    return false;
                }
            } catch (error) {
                console.error('获取最近活动数据失败:', error);
                return false;
            } finally {
                this.loading = false;
            }
        },

        async loadMoreActivities() {
            if (this.loading || !this.hasMore) return false;

            const nextPage = this.page + 1;
            return await this.fetchRecentActivities(null, nextPage);
        },

        async fetchLocationActivities(locationId) {
            if (!locationId) {
                // 如果未提供locationId，尝试从localStorage获取
                const storedLocationId = localStorage.getItem('currentLocationId');
                if (storedLocationId) {
                    locationId = storedLocationId;
                    console.log('从localStorage获取位置ID:', locationId);
                } else {
                    console.warn('未提供位置ID且localStorage中也没有，无法获取位置活动');
                    return [];
                }
            }

            this.loading = true;

            try {
                console.log(`获取位置ID ${locationId} 的活动数据`);

                const response = await messagesApi.getMessages({
                    locationId: locationId,
                    page: 1,
                    pageSize: this.pageSize
                });

                if (response && response.code === 200 && response.data) {
                    // 转换后端数据格式为前端格式
                    const allMessages = response.data.list || [];
                    const activityList = allMessages.filter(item =>
                        item.messageType === 'activity' &&
                        ['create', 'update', 'delete', 'move', 'login', 'logout', 'permission'].includes(item.subType)
                    );

                    const mappedActivities = activityList.map(item => ({
                        id: item.id,
                        title: item.title,
                        content: item.content,
                        actionType: item.subType,
                        time: item.createTime,
                        userName: item.userName,
                        locationName: item.locationName,
                        userId: item.userId,
                        locationId: item.locationId,
                        itemId: item.itemId,
                        itemName: item.itemName
                    }));

                    console.log(`成功获取位置ID ${locationId} 的活动数据: ${mappedActivities.length} 条记录`);
                    return mappedActivities;
                } else {
                    console.warn('API返回的位置活动数据无效:', response);
                    // 从当前状态中过滤特定位置的活动
                    const locationActivities = this.activities.filter(activity =>
                        activity.locationId === locationId
                    );
                    return locationActivities;
                }
            } catch (error) {
                console.error('获取位置活动数据失败:', error);
                return [];
            } finally {
                this.loading = false;
            }
        },

        // 记录新活动
        async recordActivity(activity) {
            try {
                // 准备活动数据，适配后端格式
                const messageData = {
                    messageType: 'activity',
                    title: activity.title,
                    content: activity.content,
                    subType: activity.actionType,
                    userName: activity.userName || '系统',
                    locationId: activity.locationId,
                    isRead: 0  // 添加isRead字段，默认为未读状态
                };

                // 添加可选字段
                if (activity.userId) messageData.userId = activity.userId;
                if (activity.locationName) messageData.locationName = activity.locationName;
                if (activity.itemId) messageData.itemId = activity.itemId;
                if (activity.itemName) messageData.itemName = activity.itemName;

                console.log('发送到 messagesApi 的 messageData:', JSON.parse(JSON.stringify(messageData)));

                const response = await messagesApi.createMessage(messageData);

                if (response && response.code === 200 && response.data) {
                    console.log('创建活动记录成功，返回数据:', response.data);
                    if (response.data.id) {
                        console.log('新创建的消息ID:', response.data.id);
                    } else {
                        console.warn('服务器返回成功，但没有返回消息ID');
                    }
                    // 不再添加到本地状态，每次需要时从服务器获取最新数据
                    return true;
                } else {
                    console.warn('创建活动记录失败:', response);
                    return false;
                }
            } catch (error) {
                console.error('创建活动记录出错:', error);
                return false;
            }
        }
    }
}) 